using Dapper;
using Finance.Api.Read.Applications.Commands.财务管理;
using Finance.Api.Read.Dtos;
using Finance.Domain;
using Finance.ErrorCode;
using Finance.Infrastructure;
using MediatR;
using System.Text;

namespace Finance.Api.Read.Applications.CommandHands.财务管理
{
    public class ReceiveQueryCommandHandlers : IRequestHandler<ReceiveQueryCommand, ApiResult<ApiPaging<List<ReceiveDto>>>>
    {
        private readonly IDapperDb _db;
        private readonly ILogger<ReceiveQueryCommandHandlers> _logger;

        public ReceiveQueryCommandHandlers(IDapperDb db, ILogger<ReceiveQueryCommandHandlers> logger)
        {
            _db = db;
            _logger = logger;
        }

        public async Task<ApiResult<ApiPaging<List<ReceiveDto>>>> Handle(ReceiveQueryCommand request, CancellationToken cancellationToken)
        {
            var result=new ApiResult<ApiPaging<List<ReceiveDto>>>();
            StringBuilder stringBuilder = new StringBuilder();
            StringBuilder Totalnum = new StringBuilder();

            ApiPaging<List<ReceiveDto>> res=new ApiPaging<List<ReceiveDto>>();
            var paramenters = new DynamicParameters();
            try
            {
                stringBuilder.Append(@"SELECT a.Id,
                            a.CustomerId,
                            a.ReceiptAmount,
                            a.ReceiptAccount,
                            a.IsInvoice,
                            a.AdvanceDate,
                            a.AdvancePerson,
                            a.RelatedProject,
                            a.Remarks,
                            b.CustomerName AS CustomerName,
                            a.CreateName,
                            a.CreateTime,
                            a.UpdateName,
                            a.UpdateTime,
                            a.DeleteName,
                            a.DeleteTime
                    FROM FinanceReceive a
                    LEFT JOIN Customer b
                        ON a.CustomerId=b.Id
                    WHERE 1=1
                            AND a.IsDelete=0 ");
                if (!string.IsNullOrEmpty(request.CustomenName))
                {
                    stringBuilder.Append(" and b.CustomerName LIKE @CustomenName ");
                    paramenters.Add("CustomenName", $"%{request.CustomenName}%");
                }
                if (request.Isnoves > 0)
                {
                    stringBuilder.Append(" and  a.IsInvoice = @Isnoves ");
                    paramenters.Add("Isnoves", $"{request.Isnoves}");
                }
                Totalnum.Append(@"SELECT COUNT(1)
                            FROM FinanceReceive ");
                if (!string.IsNullOrEmpty(request.CustomenName))
                {
                    stringBuilder.Append(" and b.CustomerName LIKE @CustomenName ");
                }
                if (request.Isnoves > 0)
                {
                    stringBuilder.Append(" and a.IsInvoice = @Isnoves ");
                }
                int totalcount = await _db.QueryFirst<int>(Totalnum.ToString(), paramenters);
                stringBuilder.Append($"order by a.Id DESC offset ({request.index - 1})*{request.size} rows fetch next {request.size} rows only");

                var list = await _db.Query<ReceiveDto>(stringBuilder.ToString(), paramenters);
                res.data = list.ToList();
                res.totalcount = totalcount;
                res.totalpcount = (int)Math.Ceiling(totalcount * 1.0 / request.size);
                result.data = res;
                result.message = "分页查询成功";
                result.Code = Enumcode.ok;
            }
            catch (Exception ex)
            {
                _logger.LogError("=>",ex.Message);
                result.message = "分页查询失败";
                result.Code = Enumcode.fail;
                throw;
            }
           
            return await  Task.FromResult(result);
        }
    }
}
